package com.emm.yixun.mobile.ui.personal;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.EditMemberInfo;
import com.emm.yixun.mobile.model.GetMemberInfo;
import com.eroad.product.tools.PopuContent;
import com.eroad.product.tools.Time_SelectPicPopupWindow;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nui.multiphotopicker.view.ImageBucketChooseActivity;
import com.yanzhenjie.album.Album;
import com.yixun.app.viewpagerandimag.sample.ViewPagerActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.CropOption;
import xf.tools.CropOptionAdapter;
import xf.tools.Loading;
import xf.tools.RoundImageView;

/**
 * <p>
 * <b>Title：</b> 个人详情
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午4:04:37
 */
public class PersonalDateActivity extends SwipeBackActivity {

    private static final String TAG = "PersonalDateActivity";

    /**
     * 标题
     */
    TextView title_main;

    /**
     * 退出登录
     */
    TextView exit_app;

    /**
     * 生日
     */
    TextView birthday_view;

    /**
     * 头像菜单
     */
    RelativeLayout image_menu;

    /**
     * 头像菜单
     */
    public View view3;

    /**
     * 头像菜单
     */
    public PopupWindow popu_phone;

    /**
     * 拍照图片路径
     */
    private Uri mImageCaptureUri;

    RoundImageView personal_image;

    /**
     * 修改密码按钮
     */
    TextView update_pwd;

    /**
     * 返回按钮
     */
    ImageView back_btn;

    private static final int PICK_FROM_CAMERA = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int PICK_FROM_FILE = 3;

    private static final int PIC_CODE = 993;

    /**
     * 自定义时间控件
     */
    private Time_SelectPicPopupWindow time_SelectPicPopupWindow;

    /**
     * 个人信息
     */
    GetMemberInfo getinfo;

    /**
     * 用户名
     */
    TextView user_name;

    /**
     * 入职时间
     */
    TextView goin_day;

    // /** 缓存大小 */
    // TextView date_size;

    /**
     * 清理缓存
     */
    LinearLayout clear_all_date;

    TextView update_view;

    /**
     * 关于
     */
    TextView about_view;

    /**
     * 反馈
     */
    TextView feedback_view;

    /**
     * 侧滑关闭框架
     */
    private SwipeBackLayout mSwipeBackLayout;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_personaldate);

        SetSwipeBackLayout(mSwipeBackLayout);

        BaseActivity.activity = this;
        initView();
        initBtn();
        getMemberInfo();
    }

    /**
     * <p>
     * <b>Title：</b> 初始化view
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:20:39
     */
    private void initView() {
        exit_app = (TextView) findViewById(R.id.exit_app);
        image_menu = (RelativeLayout) findViewById(R.id.image_menu);
        personal_image = (RoundImageView) findViewById(R.id.personal_image);
        birthday_view = (TextView) findViewById(R.id.birthday_view);
        update_pwd = (TextView) findViewById(R.id.update_pwd);
        title_main = (TextView) findViewById(R.id.title_main);
        title_main.setText(getString(R.string.personal_title));
        back_btn = (ImageView) findViewById(R.id.back_btn);
        back_btn.setVisibility(View.VISIBLE);
        user_name = (TextView) findViewById(R.id.user_name);
        goin_day = (TextView) findViewById(R.id.goin_day);
        clear_all_date = (LinearLayout) findViewById(R.id.clear_all_date);
        update_view = (TextView) findViewById(R.id.update_view);
        about_view = (TextView) findViewById(R.id.about_view);
        feedback_view = (TextView) findViewById(R.id.feedback_view);
        RelativeLayout main_head_top_rela = (RelativeLayout) findViewById(R.id.personaldate_include)
                .findViewById(R.id.main_head_top_rela);
        SetViewHeight(main_head_top_rela);// 更改relativelayout的高度
    }

    /**
     * <p>
     * <b>Title：</b> 初始化监听事件
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:20:54
     */
    private void initBtn() {

        exit_app.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PopuContent.poPu(PersonalDateActivity.this, "确认退出?", true, 99);
            }
        });

        image_menu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出头像菜单
                popu();
            }
        });

        update_view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PersonalDateActivity.this, APKupdateActivity.class));
            }
        });

        update_pwd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PersonalDateActivity.this, UpdatePasswordActivity.class));
            }
        });
        back_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        personal_image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewPagerActivity.type = 99;
                ViewPagerActivity.sDrawables.clear();
                ViewPagerActivity.sDrawables.add(HeadPic);
                Intent intent = new Intent(PersonalDateActivity.this, ViewPagerActivity.class);
                startActivity(intent);
            }
        });
        clear_all_date.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清理缓存,方便token失效的操作
                EmmApplication.aCache.clear();
                sendBroadcast(new Intent(EmmApplication.logout));
                finish();
            }
        });

        about_view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PersonalDateActivity.this, AboutActivty.class));
            }
        });
        feedback_view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PersonalDateActivity.this, FeedBackActivity.class));
            }
        });
    }

    OnClickListener keyListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.imageView1:
                    time_SelectPicPopupWindow.dismiss();
                    time_SelectPicPopupWindow.Aprils.clear();
                    time_SelectPicPopupWindow.Years.clear();
                    time_SelectPicPopupWindow.Days.clear();

                    SimpleDateFormat formats = new SimpleDateFormat("yyyy年MM月dd日");
                    Calendar c = Calendar.getInstance();
                    try {
                        c.setTime(formats.parse(time_SelectPicPopupWindow.getLanguage()
                                + time_SelectPicPopupWindow.getType_One() + time_SelectPicPopupWindow.getType()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (EmmApplication.Month == 1) {
                        c.add(Calendar.MONTH, -1);
                    } else {
                        c.add(Calendar.MONTH, -3);
                    }

                    Date endDate = c.getTime();
                    String str = formats.format(endDate);
                    Log.w(TAG, "str:" + str);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * <p>
     * <b>Title：</b> 点击头像后的弹出框
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:21:51
     */
    @SuppressLint("WrongConstant")
    public void popu() {
        view3 = LayoutInflater.from(PersonalDateActivity.this).inflate(R.layout.item_popupwindow, null);
        popu_phone = new PopupWindow(view3, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        popu_phone.setFocusable(true);

        // EmmApplication.setNumberLog(PersonalDateActivity.this, 0.5f);

        popu_phone.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popu_phone.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        popu_phone.showAtLocation(view3, Gravity.BOTTOM, 0, 0);
        popu_phone.showAsDropDown(view3, 0, 0);
        popu_phone.setFocusable(true);
        popu_phone.setOutsideTouchable(true);
        view3.setFocusable(true);
        view3.setFocusableInTouchMode(true);

        view3.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popu_phone.dismiss();
                    EmmApplication.setLog(PersonalDateActivity.this);
                }
                return false;
            }
        });

        view3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popu_phone.dismiss();
                EmmApplication.setLog(PersonalDateActivity.this);
            }
        });

        // 拍照
        Button camera = (Button) view3.findViewById(R.id.item_popupwindows_camera);
        // 相册
        Button photo = (Button) view3.findViewById(R.id.item_popupwindows_Photo);
        // 取消
        Button cancel = (Button) view3.findViewById(R.id.item_popupwindows_cancel);

        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popu_phone.dismiss();
                EmmApplication.setLog(PersonalDateActivity.this);
            }
        });
        camera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popu_phone.dismiss();
                EmmApplication.setLog(PersonalDateActivity.this);
                Album.camera(activity).start(PIC_CODE);
            }
        });
        photo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EmmApplication.bitmap = null;
                popu_phone.dismiss();
                EmmApplication.setLog(PersonalDateActivity.this);
                EmmApplication.setData("Picture", "1");
                EmmApplication.IsMoreSelect = false;
                startActivity(new Intent(PersonalDateActivity.this, ImageBucketChooseActivity.class));
            }
        });
    }

    /**
     * 回调方法
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.w("a", +requestCode + "resultCode===" + resultCode + "RESULT_OK======" + RESULT_OK);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case PICK_FROM_CAMERA:
                Log.w("a", "拍照");
                if (data != null)
                    mImageCaptureUri = data.getData();
                doCrop();
                break;
            case PICK_FROM_FILE:
                Log.w("a", "相册");
                mImageCaptureUri = data.getData();
                doCrop();
                break;
            case CROP_FROM_CAMERA:
                Log.w("CROP_FROM_CAMERA", "CROP_FROM_CAMERA");
                if (null != data) {
                    saveCutPic(data);
                }
                break;
            case 0:
                System.out.println("相册");
                break;
            case PIC_CODE:
                String path = Album.parseResult(data).get(0);
                editMemberInfo(EmmApplication.setPatchRtString(path));
                break;
            default:
                break;
        }
    }

    /**
     * <p>
     * <b>Title：</b> 剪切
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:22:08
     */
    private void doCrop() {
        final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");
        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
        int size = list.size();
        if (size == 0) {
            return;
        } else {
            intent.setData(mImageCaptureUri);
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);
            if (size == 1) {
                Intent i = new Intent(intent);
                ResolveInfo res = list.get(0);
                i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                startActivityForResult(i, CROP_FROM_CAMERA);
            } else {
                for (ResolveInfo res : list) {
                    final CropOption co = new CropOption();
                    co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                    co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                    co.appIntent = new Intent(intent);
                    co.appIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                    cropOptions.add(co);
                }

                CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Choose Crop App");
                builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        startActivityForResult(cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
                    }
                });
                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (mImageCaptureUri != null) {
                            getContentResolver().delete(mImageCaptureUri, null, null);
                            mImageCaptureUri = null;
                        }
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        }
    }

    /**
     * <p>
     * <b>Title：</b> 获取返回的图片并修改
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param picData
     * @author tangxin
     * @date 2016年12月7日 下午4:22:29
     */
    private void saveCutPic(Intent picData) {
        Bundle bundle = picData.getExtras();
        if (null != bundle) {
            Bitmap mBitmap = bundle.getParcelable("data");
            personal_image.setImageBitmap(mBitmap);
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
                byte[] datas = baos.toByteArray();
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byte[] encode = Base64.encode(datas, Base64.DEFAULT);
                String photo2 = new String(encode);
                EmmApplication.setData("uri_byte", photo2);
                Log.v("相机获取:phone_date：", photo2);
                editMemberInfo(photo2);
            } catch (Exception e) {
            }
        }
        File f = new File(mImageCaptureUri.getPath());
        if (f.exists()) {
            f.delete();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseActivity.activity = this;
        if (EmmApplication.bitmap != null) {
            personal_image.setImageBitmap(EmmApplication.bitmap);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            EmmApplication.bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
            byte[] datas = baos.toByteArray();
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] encode = Base64.encode(datas, Base64.DEFAULT);
            String photo2 = new String(encode);
            EmmApplication.setData("uri_byte", photo2);// 获取之后直接上传
            Log.w(TAG, "相册获取到的==》" + photo2);
            editMemberInfo(photo2);
        }

        IntentFilter filter = new IntentFilter(EmmApplication.logout);
        registerReceiver(mBroadcastReceiver, filter);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(EmmApplication.logout)) {
                finish();
            }
        }
    };

    protected void onDestroy() {
        unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
    }

    ;

    /**
     * <p>
     * <b>Title：</b> 个人信息查询接口
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:23:07
     */
    private void getMemberInfo() {
        EmmApplication.updateUrl("getMemberInfo");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getMemberInfo-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(PersonalDateActivity.this, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                getinfo = JSONObject.parseObject(resData.toString(), GetMemberInfo.class);

                if ("1".equals(getinfo.getResult())) {
                    Log.v("获取成功", "");
                    try {
                        HeadPic = getinfo.getHeadPic();
                    } catch (NullPointerException e) {
                        Log.v(TAG, "头像链接为空");
                    }
                    EmmApplication.image(R.drawable.touxiang);
                    EmmApplication.imageLoader.displayImage(getinfo.getHeadPic(), personal_image, EmmApplication.options);
                    birthday_view.setText(getinfo.getBirthday());
                    user_name.setText(getinfo.getName());
                    goin_day.setText(getinfo.getEntryTime());
                    // user_phone.setText(getinfo.getMobile());

                } else {
                    EmmApplication.T(getinfo.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getinfo.getErrorCode().toString() + "errorMsg:"
                            + getinfo.getErrorMsg().toString());
                }
            }
        });
    }

    String HeadPic = "1";
    EditMemberInfo editmember;

    /**
     * <p>
     * <b>Title：</b> 个人信息查询修改
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param headPic
     * @author tangxin
     * @date 2016年12月7日 下午4:23:25
     */
    private void editMemberInfo(String headPic) {
        EmmApplication.updateUrl("editMemberInfo");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("headPic", headPic);
        map.put("headType", ".jpg");
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("editMemberInfo-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(PersonalDateActivity.this, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                editmember = JSONObject.parseObject(resData.toString(), EditMemberInfo.class);

                if ("1".equals(getinfo.getResult())) {
                    Log.v("获取成功", "");
                    EmmApplication.bitmap = null;
                    getMemberInfo();
                } else {
                    EmmApplication.T(editmember.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + editmember.getErrorCode().toString() + "errorMsg:"
                            + editmember.getErrorMsg().toString());
                }
            }
        });
    }

}
